﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WD.Classes;
using System.Collections;
using WD.Properties;
using System.Security.Policy;
using System.Security.Cryptography;
using WDutils;
using System.Threading;

namespace WD
{
    public partial class MainForm : Form
    {
        private PrintPenalty dataGridPrinter1 = null;
        private settingsForm objSettingsFrom = null;
        private QuickAdd objQuickAddForm = null;
        private ExportFrm objExportForm = null;
        private Report objReportsForm = null;

        public MainForm()
        {
            InitializeComponent();

            ErrorMessage.debugMode = Properties.Settings.Default.debugMode;

            this.Text = Resources.TXT_MAIN_FORM_TITLE;
            GB_ActivityLog.Text = Resources.GB_ActivityLog;
            GB_Filter.Text = Resources.GB_Filter;
            L_ActivityLog_Text.Text = Resources.L_ActivityLog_Text;
            CB_EnableTimeFilter.Text = Resources.CB_EnableTimeFilter;

            L_ActivityLog_ID.Text = Resources.L_ActivityLog_ID;
            B_ActivityLog_Save.Text = Resources.B_ActivityLog_Save;
            B_ActivityLog_Insert.Text = Resources.B_ActivityLog_Insert;
            B_ActivityLog_Delete.Text = Resources.B_ActivityLog_Delete;

            B_ActivityLog_PermanentDelete.Text = Resources.B_ActivityLog_PermanentDelete;
            B_ActivityLog_Restore.Text = Resources.B_ActivityLog_Restore;

            B_Print_ActivityLog.Text = Resources.B_Print_ActivityLog;
            B_Print_ActivityLog_Preview.Text = " ";

            L_CreatedOn_DateTime.Text = Properties.Resources.TXT_ACTIVITY_LOG_CREATED_ON;
            L_ModifiedOn_DateTime.Text = Properties.Resources.TXT_ACTIVITY_LOG_MODIFIED_ON;
            L_DeletedOn_DateTime.Text = Properties.Resources.TXT_ACTIVITY_LOG_DELETED_ON;

            timerNotify.Interval = 60 * 1000 * (int)Properties.Settings.Default.ACTIVITY_LOG_REMIND_AFTER_MINUTES;

            objQuickAddForm = new QuickAdd();
            //objQuickAddForm.Hide();

            objExportForm = new ExportFrm();
            objReportsForm = new Report();

            ContextMenu rightClickMenu = new ContextMenu();
            
            MenuItem mnuRestore = new MenuItem("Restore");
            MenuItem mnuExit = new MenuItem("Exit");

            mnuRestore.Click += new EventHandler(mnuRestore_Click);
            mnuExit.Click += new EventHandler(mnuExit_Click);

            rightClickMenu.MenuItems.AddRange(new MenuItem[] { mnuRestore, mnuExit });

            notifyIconMain.ContextMenu = rightClickMenu;
        }

        private void mnuRestore_Click(object sender, EventArgs e)
        {
            restoreMainForm();
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        void SetupGridPrinter()
        {
            //DataGrid dg = new DataGrid();
            //dg.DataSource = DGV_Penalties.DataSource;
            //DataTable dt = new DataTable();
            //if (DGV_Penalties.Columns.Contains("ID")) DGV_Penalties.Columns.Remove("ID");
            //dt = Utils.Data.GetDataTableFromDGV(DGV_Penalties);
            //dataGridPrinter1 = new PrintPenalty(dg, printDocumentPenalty, dt);
        }

        private void ReloadActivityLogDGV()
        {
            ActivityLogEvents.GetAllActivityLog2GridView evGetActivities2Grid = new ActivityLogEvents.GetAllActivityLog2GridView(DGV_ActivityLog, cbShowDeleted.Checked);
            if (CB_EnableTimeFilter.Checked) evGetActivities2Grid.setGetCondition_TimeFilter(DTP_Filter.Value);
            if (TB_Search.Text.Trim() != "") evGetActivities2Grid.setGetCondition_TextSearch(TB_Search.Text);
            evGetActivities2Grid.Request();

            ActivityLogEvents.GetActivityLogWorkingHoursPerDay evWHpD = new ActivityLogEvents.GetActivityLogWorkingHoursPerDay();
            evWHpD.setDay(DTP_Filter.Value);
            List<double> listWH = (List<double>)(evWHpD.Request());

            L_Main_WH_Info.ForeColor = Color.Black;
            if (listWH[0].ToString("#.##") != "")
            {
                L_Main_WH_Info.Text = "Worked for " + listWH[0].ToString("#.##") + " hour(s)";
                if (listWH[0] > Report.WORKING_HOUR_OVERTIME_TRESHOLD) L_Main_WH_Info.ForeColor = Color.Red;
                else
                    if (listWH[0] > Report.WORKING_HOUR_UNDERTIME_TRESHOLD) L_Main_WH_Info.ForeColor = Color.Green;
            }
            else L_Main_WH_Info.Text = "No work.";

            DGV_ActivityLog.Sort(DGV_ActivityLog.Columns[1], ListSortDirection.Ascending);
        }
       
        private void MainForm_Load(object sender, EventArgs e)
        {
            string serialNo = Utils.Security.getIdentifier("Win32_DiskDrive", "Model").ToString();
            if (Utils.Security._encode(serialNo) != Properties.Settings.Default.WD_SERIAL_KEY)
            {
                MessageBox.Show(String.Format( Resources.TXT_SECURITY_LICENSE_REFUSE, serialNo, Properties.Settings.Default.WD_SERIAL_KEY));
                Application.Exit();
            }
            //TB_Person_Name.Text = Utils.Security._encode(serialNo);

            ReloadActivityLogDGV();

            if (true) //Setting - startup minimized
            {
                //this.WindowState = FormWindowState.Normal;
                this.WindowState = FormWindowState.Minimized;
                //this.Hide();
            }
        }

        private void DGV_ActivityLog_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex.ToString() != "-1")
            {
                String strActivityLogID = DGV_ActivityLog.Rows[e.RowIndex].Cells[0].Value.ToString();

                ActivityLogEvents.GetActivityLog eventGetActivityLog = new ActivityLogEvents.GetActivityLog();
                eventGetActivityLog.setShowDeleted(cbShowDeleted.Checked);
                eventGetActivityLog.setID(strActivityLogID);

                ActivityLog activityLog = eventGetActivityLog.Request();

                TB_ActivityLog_Text.Text = activityLog.getText();
                L_ActivityLog_ID.Text = Resources.L_ActivityLog_ID + " : ";
                L_ActivityLog_ID_Value.Text = activityLog.getID();

                B_ActivityLog_Save.Enabled = true;

                if (activityLog.getDeletedOnDateTime2String() == "-")
                {
                    B_ActivityLog_Delete.Enabled = true;

                    B_ActivityLog_Delete.Visible = true;
                    B_ActivityLog_PermanentDelete.Visible = false;
                    B_ActivityLog_Restore.Visible = false;
                }
                else{
                    B_ActivityLog_Delete.Visible = false;
                    B_ActivityLog_PermanentDelete.Visible = true;
                    B_ActivityLog_Restore.Visible = true;
                }

                L_CreatedOn_DateTime.Text = Properties.Resources.TXT_ACTIVITY_LOG_CREATED_ON + " : " + activityLog.getCreatedOnDateTime().ToLocalTime().ToString();
                L_ModifiedOn_DateTime.Text = Properties.Resources.TXT_ACTIVITY_LOG_MODIFIED_ON + " : " + activityLog.getModifiedOnDateTime().ToLocalTime().ToString();
                L_DeletedOn_DateTime.Text = Properties.Resources.TXT_ACTIVITY_LOG_DELETED_ON + " : " + activityLog.getDeletedOnDateTime2String();
            }
        }

        private void resetUI()
        {
            L_ActivityLog_ID_Value.Text = "-";

            B_ActivityLog_Save.Enabled = false;

            B_ActivityLog_Delete.Enabled = false;
            B_ActivityLog_Delete.Visible = true;

            B_ActivityLog_PermanentDelete.Visible = false;
            B_ActivityLog_Restore.Visible = false;
        }

        #region CRUD button operations controll center
        
        private void B_ActivityLog_Save_Click(object sender, EventArgs e)
        {
            ActivityLog objUpdateActivityLog = new ActivityLog();
            objUpdateActivityLog.setID(L_ActivityLog_ID_Value.Text);
            objUpdateActivityLog.setText(TB_ActivityLog_Text.Text);

            ActivityLogEvents.UpdateActivityLog eventUpdateActivityLog = new ActivityLogEvents.UpdateActivityLog(objUpdateActivityLog);
            eventUpdateActivityLog.Publish();

            //Refresh Table.
            ReloadActivityLogDGV();
        }

        private void B_ActivityLog_Insert_Click(object sender, EventArgs e)
        {
            ActivityLog objInsertActivityLog = new ActivityLog();
            objInsertActivityLog.setText(TB_ActivityLog_Text.Text);

            ActivityLogEvents.InsertActivityLog eventInsertActivityLog = new ActivityLogEvents.InsertActivityLog(objInsertActivityLog);
            eventInsertActivityLog.Publish();

            resetUI();
        
            //Refresh Table.
            ReloadActivityLogDGV();
        }

        private void B_ActivityLog_Delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Resources.TXT_DELETE_CONFIRMATION, Resources.TXT_CONFIRMATION_TITLE, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                ActivityLogEvents.DeleteActivityLog eventDelete = new ActivityLogEvents.DeleteActivityLog(L_ActivityLog_ID_Value.Text);
                eventDelete.Publish();

                resetUI();

                //Refresh Table.
                ReloadActivityLogDGV();
            }
        }

        private void B_ActivityLog_Restore_Click(object sender, EventArgs e)
        {
            ActivityLogEvents.RestoreActivityLog eventRestore = new ActivityLogEvents.RestoreActivityLog(L_ActivityLog_ID_Value.Text);
            eventRestore.Publish();
            
            ReloadActivityLogDGV();
        }

        private void B_ActivityLog_PermanentDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Resources.TXT_DELETE_CONFIRMATION, Resources.TXT_CONFIRMATION_TITLE, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                ActivityLogEvents.PermanentDeleteActivityLog eventDelete = new ActivityLogEvents.PermanentDeleteActivityLog(L_ActivityLog_ID_Value.Text);
                eventDelete.Publish();

                resetUI();

                //Refresh Table.
                ReloadActivityLogDGV();
            }
        }

#endregion

        private void DGV_ActivityLog_SelectionChanged(object sender, EventArgs e)
        {
            if (DGV_ActivityLog.SelectedRows.Count > 0)
            {
                String strActivityLogID = DGV_ActivityLog.SelectedRows[0].Cells[0].Value.ToString();

                ActivityLogEvents.GetActivityLog eventGetActivityLog = new ActivityLogEvents.GetActivityLog();
                eventGetActivityLog.setID(strActivityLogID);

                ActivityLog activityLog = eventGetActivityLog.Request();

                TB_ActivityLog_Text.Text = activityLog.getText();
                L_ActivityLog_ID.Text = Resources.L_ActivityLog_ID + " : ";
                L_ActivityLog_ID_Value.Text = activityLog.getID();
            }
        }


        private void B_Print_ActivityLog_Click(object sender, EventArgs e)
        {
            SetupGridPrinter();

            dataGridPrinter1.PageNumber = 1;
            dataGridPrinter1.RowCount = 0;
            if (printDialog1.ShowDialog() == DialogResult.OK)
            {
                printDocumentPenalty.Print();
            }

            //ReloadPenaltiesIfPersAndVersionSelected();

        }

        private void printDocumentPenalty_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;
            DrawTopLabel(g);
            bool more = dataGridPrinter1.DrawDataGrid(g);
            if (more == true)
            {
                e.HasMorePages = true;
                dataGridPrinter1.PageNumber++;
            }
            DrawTotalLabel(g);
        }

        void DrawTopLabel(Graphics g)
        {
            //Int32 lines;
        	//Int32 chars;
            //Use the StringFormat class for the text layout of our document
    	    StringFormat format = new StringFormat(StringFormatFlags.LineLimit);

            int TopMargin = printDocumentPenalty.DefaultPageSettings.Margins.Top;

            int printHeight = dataGridPrinter1.DefaultPageSettings.PaperSize.Height - dataGridPrinter1.DefaultPageSettings.Margins.Top - dataGridPrinter1.DefaultPageSettings.Margins.Bottom;
            int printWidth = dataGridPrinter1.DefaultPageSettings.PaperSize.Width - dataGridPrinter1.DefaultPageSettings.Margins.Left - dataGridPrinter1.DefaultPageSettings.Margins.Right;

            int leftMargin = dataGridPrinter1.DefaultPageSettings.Margins.Left;  //X
            int rightMargin = dataGridPrinter1.DefaultPageSettings.Margins.Top;  //Y

            RectangleF printArea = new RectangleF(leftMargin, rightMargin, printWidth, printHeight);
            
            //g.FillRectangle(new SolidBrush(Color.White), 200, 50 + TopMargin, 100, 50);

            //printArea.X += 120;
            //g.MeasureString(Properties.Settings.Default.PRINT_PENALTY_TITLE, new Font("Arial", 14), new SizeF(printWidth, printHeight), format, out chars, out lines);
            //g.DrawString(Properties.Settings.Default.PRINT_PENALTY_TITLE, new Font("Arial", 14), new SolidBrush(Color.Black), printArea, format);
            //printArea.X -= 120;

            //printArea.Y += 30;

            //printArea.X += 150;
            //g.MeasureString(Properties.Settings.Default.PRINT_DOMAIN, new Font("Arial", 12), new SizeF(printWidth, printHeight), format, out chars, out lines);
            //g.DrawString(Properties.Settings.Default.PRINT_DOMAIN, new Font("Arial", 12), new SolidBrush(Color.Black), printArea, format);
            //printArea.X -= 150;

            //printArea.Y += 60;

            //g.MeasureString(((Utils.ComboItem)(CB_PersonSelector.SelectedItem)).getName(), new Font("Arial", 12), new SizeF(printWidth, printHeight), format, out chars, out lines);
            //g.DrawString(((Utils.ComboItem)(CB_PersonSelector.SelectedItem)).getName(), new Font("Arial", 12), new SolidBrush(Color.Black), printArea, format);


        }

        void DrawTotalLabel(Graphics g)
        {
            //Int32 lines;
            //Int32 chars;
            //Use the StringFormat class for the text layout of our document
            StringFormat format = new StringFormat(StringFormatFlags.LineLimit);

            int TopMargin = printDocumentPenalty.DefaultPageSettings.Margins.Top;

            int printHeight = dataGridPrinter1.DefaultPageSettings.PaperSize.Height - dataGridPrinter1.DefaultPageSettings.Margins.Top - dataGridPrinter1.DefaultPageSettings.Margins.Bottom;
            int printWidth = dataGridPrinter1.DefaultPageSettings.PaperSize.Width - dataGridPrinter1.DefaultPageSettings.Margins.Left - dataGridPrinter1.DefaultPageSettings.Margins.Right;

            int leftMargin = dataGridPrinter1.DefaultPageSettings.Margins.Left;  //X
            int rightMargin = dataGridPrinter1.DefaultPageSettings.Margins.Top;  //Y

            RectangleF printArea = new RectangleF(75, printHeight+50, printWidth, printHeight);

            //g.MeasureString(L_Penalty_Rate_Total.Text + L_Penalty_Rate_Total_Value.Text + "                      " + L_Penlaty_Penalty_Total.Text + L_Penlaty_Penalty_Total_Value.Text, new Font("Arial", 10), new SizeF(printWidth, printHeight), format, out chars, out lines);
            //g.DrawString(L_Penalty_Rate_Total.Text + L_Penalty_Rate_Total_Value.Text + "                      " + L_Penlaty_Penalty_Total.Text + L_Penlaty_Penalty_Total_Value.Text, new Font("Arial", 10), new SolidBrush(Color.Black), printArea, format);

            //printArea.X += 500;
            //g.MeasureString(L_Penalty_Total.Text + L_Penalty_Total_Value.Text, new Font("Arial", 14), new SizeF(printWidth, printHeight), format, out chars, out lines);
            //g.DrawString(L_Penalty_Total.Text + L_Penalty_Total_Value.Text, new Font("Arial", 14), new SolidBrush(Color.Black), printArea, format);
            //printArea.X -= 500;

            //printArea.Y += 50;
            //printArea.X += 300;
            //g.MeasureString("-" + DateTime.Now.ToString("dd.MM.yyyy") + "-", new Font("Arial", 10), new SizeF(printWidth, printHeight), format, out chars, out lines);
            //g.DrawString("-" + DateTime.Now.ToString("dd.MM.yyyy") + "-", new Font("Arial", 10), new SolidBrush(Color.Black), printArea, format);
        }

        private void B_Print_ActivityLog_Preview_Click(object sender, EventArgs e)
        {
            SetupGridPrinter();

            dataGridPrinter1.PageNumber = 1;
            dataGridPrinter1.RowCount = 0;
            if (this.printPreviewDialog1.ShowDialog() == DialogResult.OK)
            {
            }

            //ReloadPenaltiesIfPersAndVersionSelected();

        }

        private void printPreviewDialog1_Load(object sender, EventArgs e)
        {
            printPreviewDialog1.Bounds = ClientRectangle;
        }

        
        private void B_VersionShow_Click(object sender, EventArgs e)
        {
            AboutWD aboutWD = new AboutWD();
            aboutWD.ShowDialog();
        }


        private void TB_ActivityLog_Text_Enter(object sender, EventArgs e)
        {
            TB_ActivityLog_Text.BackColor = Color.Moccasin;
        }

        private void TB_ActivityLog_Text_Leave(object sender, EventArgs e)
        {
            TB_ActivityLog_Text.BackColor = SystemColors.Window;
        }

        private void B_Settings_Click(object sender, EventArgs e)
        {
            if (objSettingsFrom == null)
            {
                objSettingsFrom = new settingsForm();
                objSettingsFrom.StartPosition = FormStartPosition.CenterScreen;
                objSettingsFrom.FormClosed += new FormClosedEventHandler(objSettingsFrom_FormClosed);
                objSettingsFrom.ShowDialog();
            }
            else objSettingsFrom.Focus();
        }

        private void objSettingsFrom_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.objSettingsFrom = null;
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == this.WindowState)
            {
                notifyIconMain.BalloonTipText = Properties.Resources.TXT_NOTIFY_MINIMIZE_DESCRIPTION;
                notifyIconMain.BalloonTipTitle = Properties.Resources.TXT_NOTIFY_TITLE;
                notifyIconMain.BalloonTipIcon = ToolTipIcon.Info;

                notifyIconMain.Visible = true;
                notifyIconMain.ShowBalloonTip(1);
                
                this.Hide();
            }
            else if (FormWindowState.Normal == this.WindowState)
            {
                ReloadActivityLogDGV();
                notifyIconMain.Visible = false;
            }
        }

        private void quickAddPopUp()
        {
            objQuickAddForm.Show();
            objQuickAddForm.Focus();
            objQuickAddForm.dtQuickAddDate.Value = DateTime.Now;
            objQuickAddForm.tbQuickAddText.Text = "";
            objQuickAddForm.WindowState = FormWindowState.Normal;

            objQuickAddForm.tbQuickAddText.Focus();
        }

        private void restoreMainForm()
        {
            notifyIconMain.Visible = false;
            if (objQuickAddForm.Visible) objQuickAddForm.Hide();
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Focus();
        }

        private void notifyIconMain_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            restoreMainForm();
        }

        private void notifyIconMain_Click(object sender, EventArgs e)
        {
            if (MouseButtons.Left == ((MouseEventArgs)e).Button)
            {
                quickAddPopUp();
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            notifyIconMain.Visible = false;
            notifyIconMain.Dispose();
        }

        private void notifyIconMain_BalloonTipClicked(object sender, EventArgs e)
        {

            if ((Control.MouseButtons & MouseButtons.Left) == MouseButtons.Left)
            {
                quickAddPopUp();
            }
        }

        private void timerNotify_Tick(object sender, EventArgs e)
        {
            notifyIconMain.ShowBalloonTip(3000, Properties.Resources.TXT_REMINDER_TITLE, Properties.Resources.TXT_REMINDER_DESC, ToolTipIcon.Warning);
        }

        private void cbShowDeleted_CheckedChanged(object sender, EventArgs e)
        {
            ReloadActivityLogDGV();
            resetUI();
            DGV_ActivityLog.Columns[3].Width = cbShowDeleted.Checked ? 110 : 0;
        }

        private void DTP_Filter_ValueChanged(object sender, EventArgs e)
        {
            if(CB_EnableTimeFilter.Checked) ReloadActivityLogDGV();
        }

        private void CB_EnableTimeFilter_CheckedChanged(object sender, EventArgs e)
        {
            ReloadActivityLogDGV();
        }

        private void TB_Search_TextChanged(object sender, EventArgs e)
        {
            ReloadActivityLogDGV();
        }

        private void TB_Search_KeyPress(object sender, KeyPressEventArgs e)
        {
            
        }

        private void TB_Search_KeyDown(object sender, KeyEventArgs e)
        {
            
        }

        private void B_Date_PreviousDay_Click(object sender, EventArgs e)
        {
            DTP_Filter.Value = DTP_Filter.Value.AddDays(-1);
            if (CB_EnableTimeFilter.Checked) ReloadActivityLogDGV();
        }

        private void B_Date_Today_Click(object sender, EventArgs e)
        {
            DTP_Filter.Value = DateTime.Now;
            if (CB_EnableTimeFilter.Checked) ReloadActivityLogDGV();
        }

        private void B_Date_NextDay_Click(object sender, EventArgs e)
        {
            DTP_Filter.Value = DTP_Filter.Value.AddDays(1);
            if (CB_EnableTimeFilter.Checked) ReloadActivityLogDGV();
        }

        private void B_Export_Click(object sender, EventArgs e)
        {
            objExportForm.ShowDialog();
        }

        private void B_Reports_Click(object sender, EventArgs e)
        {
            objReportsForm.ShowDialog();
        }
       
    }
}
